var simpArr={};
var alarmHight=1000;
var alarmLow=0;
var deviceValue=[];
$(document).ready(function() {
    systemFun.all_fun();
     setInterval(function(){
         systemFun.deviceInfo();
         systemFun.weathColler();
     },60000);
     setInterval(function(){
         systemFun.deviceByHour('data-swjk');
     },300000);
    setTimeout(function(){
        window.location.reload();
    },7200000);
    $(document).on("click",".big-layer",function(e){
        // $("#bigForm").html("");
         $("#bigForm").remove();
         $("#displayMain").after("<div id='bigForm' style='width: 100%;height: 100%;'></div>");
         var this_=$(this);
         var title_layer=$(this).find(".main-data-title").text();
         layer.open({
             type: 1,
            // title:[ title_layer,"font-size:18px;text-align:center;"],
             title:false,
             shadeClose: true,
             area: ['80%', '80%'],
             content: $("#bigForm"),
             success: function(index, layero) {
                 if(this_.hasClass("data-jk")){
                     $("#bigForm").html("<img src='"+(simpArr.picOne==undefined ? "" : simpArr.picOne.replace("|",""))+"' style='width: 90%; height: auto;margin-top: 5%; margin-left: 5%;'/>");
                 }else if(this_.hasClass("data-sw")){
                     $("#bigForm").html("<img src='"+(simpArr.picTwo==undefined ? "" : simpArr.picTwo.replace("|",""))+"' style='width: 90%; height: auto;margin-top: 5%; margin-left: 5%;'/>");
                 }
                 else if(this_.hasClass("data-swjk")){
                     systemFun.deviceByHour('bigForm');
                 } else if(this_.hasClass("data-3d")){
                     systemFun.draw3DChart('bigForm');
                 }
                 //$("#bigForm").show();
             }
         });

     });
    $(document).on("click",".left-content-ul > li",function(e){
        var this_=$(this).text();
        layer.open({
            type: 1,
             title:[ this_,"font-size:18px;text-align:center;"],
            shadeClose: true,
            area: ['80%', '80%'],
            content: $("#leftbig"),
            success: function(index, layero) {
                $("#leftbig").show();
            }
        });

    });
});
var systemFun=(function(){
    var all_fun=function(){
        deviceSet();
        sysImg();
        weathColler();

        deviceInfo();
        draw3DChart('data-3d');
       deviceByHour('data-swjk');
    };

    var deviceInfo=function(){
        $.ajax({
            type: "post",
            url: $("#ctx").val()+'/screen/show/deviceInfo?id='+GetQueryString("id"),
            // url: 'http://127.0.0.1:8080/jeeplus/a/screen/show/weatherInfo?id=3',
            // url: '${ctx}/weatherInfo?id=3',
            async: false,
            dataType: "json",
            success: function (data) {
                console.log(data);
                if(data){
                    deviceValue=data;
                    var strHtml="";
                    data.forEach(function(val,key){
                        var reportValue=val["reportValue"];

                        var alarmHtml="";
                        console.log(reportValue);
                        if(reportValue<alarmLow||reportValue>alarmHight){
                            alarmHtml="alarm";
                        }
                        strHtml+=`<div class="swiper-slide">
                        <li>
                            <div class="data-sj-content ${alarmHtml}">
                                <div class="data-sj-content-head">${val["deviceCode"]}</div>
                                <div class="data-sj-content-cycle-num"><em>${val["reportValue"]}</em>m</div>
                            </div>
                        </li>
                    </div>`;
                    });
                    if(data.length<4){
                        strHtml+=`<div class="swiper-slide">
                        <li>.
                            <div class="data-sj-content">
                                <div class="data-sj-content-head"></div>
                                <div class="data-sj-content-cycle-num"></div>
                            </div>
                        </li>   
                    </div>`;
                    }
                    $(".data-sj-ul").html(strHtml);
                    var mySwiper = new Swiper ('.swiper-container', {
                        slidesPerView:4,
                        autoplay:false,
                        /*autoplay:{
                            autoplay:false,//支持自动播放
                            disableOnInteraction :false,
                        },*/
                        direction: 'horizontal',
                        speed:1000,
                        loop: false,
                        delay:500
                    });
                }
            }
        });
    };
    var deviceByHour=function(containerId){
        $.ajax({
            type: "post",
            url: $("#ctx").val()+'/screen/show/deviceByHour?id='+GetQueryString("id"),
            // url: 'http://127.0.0.1:8080/jeeplus/a/screen/show/weatherInfo?id=3',
            // url: '${ctx}/weatherInfo?id=3',
            dataType: "json",
            success: function (data) {
                if(data){
                    var lendData=[];
                    for(var result in data){
                        lendData.push(result.split("|||")[1]);
                    }
                   drawWeekData(lendData,data,containerId);
                }
            }
        });
    };
    var weathColler=function(){
        $.ajax({
            type: "post",
            url: $("#ctx").val()+'/screen/show/weatherInfo?id='+GetQueryString("id"),
           // url: 'http://127.0.0.1:8080/jeeplus/a/screen/show/weatherInfo?id=3',
           // url: '${ctx}/weatherInfo?id=3',
            async: false,
            dataType: "json",
            success: function (data) {
                if(data){
                    $(".right-content-ul .temperature").text(data.temperature+"℃");
                    $(".right-content-ul .humidity").text(data.humidity+"%");
                    $(".right-content-ul .wind").text(data.wind);
                    $(".right-content-ul .speed").text(data.speed);
                    $(".right-content-ul .noise").text(data.noise+"分贝");
                    $(".right-content-ul .pressure").text(data.pressure+"mba");
                    $(".right-content-ul .pm25").text(data.pm25+"ug/m³");
                    $(".right-content-ul .pm10").text(data.pm10+"ug/m³");
                }
            }
        });
    };
    var sysImg=function(){
        $.ajax({
            type: "post",
           url: $("#ctx").val()+'/screen/show/localInfo?id='+$("#localeId").val(),
           // url: 'http://127.0.0.1:8080/jeeplus/a/screen/show/localInfo?id=3',
            async: false,
            dataType: "json",
            success: function (data) {
                if(data){
                    simpArr=data;
                    $("#data-jk img").attr("src",data.picOne==undefined ? "" : data.picOne.replace("|",""));
                    $("#data-sw img").attr("src",data.picTwo==undefined ? "" : data.picTwo.replace("|",""));

                }
            }
        });
    };
    var deviceSet=function(){
        $.ajax({
            type: "post",
            url: $("#ctx").val()+'/device/deviceSet/getById?id=1',
            // url: 'http://127.0.0.1:8080/jeeplus/a/screen/show/localInfo?id=3',
            async: false,
            dataType: "json",
            success: function (data) {
                if(data){
                    alarmHight=parseInt(data.alarmHight);
                    alarmLow=parseInt(data.alarmLow);
                    console.log("最高位:"+alarmHight);
                    console.log("最低位:"+alarmLow);
                }
            }
        });
    };
    var drawWeekData=function(lendData,data,containerId){
        var myChart = echarts.init(document.getElementById(containerId), 'macarons');
        option = {
            title:{
                show:containerId=="bigForm" ? true : false,
                text:containerId=="bigForm" ? "水位波形图" : "",
                left: 'center',
                textStyle:{
                    fontSize:24,

                },
                padding:10,
                top:'1%'
            },
            tooltip : {
                trigger: 'axis',
                axisPointer: {
                    type: 'cross',
                    label: {
                        backgroundColor: '#6a7985'
                    }
                }
            },
            legend: {
                left: 'right',
                data:lendData,
                show:containerId=="bigForm" ? true : false,
                top:'6%',
                right:'2%',
                textStyle:{
                    fontSize:18
                }

            },
            grid:function(){
                var obj={};
                if(containerId=="bigForm"){
                    obj={
                        top:'15%',
                        left: '3%',
                        right: '3%',
                        bottom: '2%',
                        containLabel: true
                    };
                }else{
                   obj= {
                       top: '2%',
                       left: '1%',
                       right: '2%',
                       bottom: '2%',
                       containLabel: true
                   }
                }
                return obj;
            }(),
            xAxis: {
                axisTick: {
                    show: false,
                    inside:true
                },
                axisLine:{
                    show:true,
                    lineStyle:{
                        color:function(){
                            if(containerId=="bigForm"){
                                return '#000';
                            }else{
                                return '#fff';
                            }
                        }(),
                        width:2
                    }
                },
                axisLabel:{
                    color:function(){
                        if(containerId=="bigForm"){
                            return '#000';
                        }else{
                            return '#fff';
                        }
                    }()
                },
                splitLine:{
                    show:false
                },
                type: 'category',
                boundaryGap: true,
                data: ['0','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16', '17', '18', '19', '20', '21','22','23'],
            },
            yAxis: {
                axisTick: {
                    show: true,
                    inside:true
                },
                axisLine:{
                    show:true,
                    lineStyle:{
                        color:function(){
                            if(containerId=="bigForm"){
                                return '#000';
                            }else{
                                return '#fff';
                            }
                        }(),
                        width:2
                    }
                },
                axisLabel:{
                    color:function(){
                        if(containerId=="bigForm"){
                            return '#000';
                        }else{
                            return '#fff';
                        }
                    }()
                },
                splitLine:{
                    show:false
                },
                boundaryGap: true,
                type: 'value'
            },
         /*  series: [{
                name:'数据1',
                data: [0, 0, 0, 0, 0, 0, 0],
                type: 'line',
                smooth: true
            },
                {
                    name:'数据2',
                    data: [0, 0, 0, 0, 0, 0, 0],
                    type: 'line',
                    smooth: true
                }]*/
           series:function(){
            var series=[];
            for(var result in data){
                var item={
                    name:result.split("|||")[1],
                    type:'line',
                    smooth:true,
                    data:function(){
                       return data[result];
                    }(),
                    markPoint: {
                        data:function(){
                            var obj=[
                                {type: 'max', name: '最大值'},
                                {type: 'min', name: '最小值'}
                            ];
                            if(containerId=="bigForm"){
                                return obj;
                            }else{
                                return "";
                            }
                        }()
                    },
                }
                series.push(item);
            }
               return series;
           }()
        };

        myChart.setOption(option,true);
        //echarts图表随着屏幕的大小自适应
        window.onresize = myChart.resize;
    };
    var draw3DChart=function (containerId){
        $.ajax({
            type: "post",
            url: $("#ctx").val()+'/app/screen/show/picture?staId='+GetQueryString("id"),
            // url: 'http://127.0.0.1:8080/jeeplus/a/screen/show/weatherInfo?id=3',
            // url: '${ctx}/weatherInfo?id=3',
            dataType: "json",
            success: function (data) {
                if(data){
                    var aConfig="";
                    var aConfigArr=[];
                    var baseConfig="";
                    var baseConfigArr=[];
                    var bConfig="";
                    var bConfigArr=[];
                    var configArr=[];
                    var configValueArr=[];

                    for (var i in data) {
                        if (data.hasOwnProperty(i) && typeof data[i] != "function") {
                            configArr.push(i);
                                   if(i=="A"){
                                       aConfigArr=data[i];
                                   }
                            if(i=="B"){
                                baseConfigArr=data[i];
                            }
                            if(i=="C"){
                                bConfigArr=data[i];
                            }
                           }
                     }
                     if(configArr.length==3){

                         var data_south=[];
                         var data_middle=[];
                         var data_north=[];
                         for(var i=0;i<aConfigArr.length;i++){
                            var tmp=[];
                            var deviceV=0;
                            for(var j=0;j<deviceValue.length;j++){
                                if(aConfigArr[i].id==deviceValue[j].deviceId){
                                    deviceV= deviceValue[j].reportValue;
                                }
                            }
                             tmp.push(parseFloat(deviceV));
                             tmp.push(aConfigArr[i].xLocation);
                             tmp.push(aConfigArr[i].order);
                             tmp.push(aConfigArr[i].color);
                             tmp.push(aConfigArr[i].code);
                             data_south.push(tmp);
                         }
                         for(var i=0;i<baseConfigArr.length;i++){
                             var tmp=[];
                             var deviceV=0;
                             for(var j=0;j<deviceValue.length;j++){
                                 if(baseConfigArr[i].id==deviceValue[j].deviceId){
                                     deviceV= deviceValue[j].reportValue;
                                 }
                             }
                             tmp.push(parseFloat(deviceV));
                             tmp.push(baseConfigArr[i].xLocation);
                             tmp.push(baseConfigArr[i].order);
                             tmp.push(baseConfigArr[i].color);
                             tmp.push(baseConfigArr[i].code);
                             data_middle.push(tmp);
                         }
                         for(var i=0;i<bConfigArr.length;i++){
                             var tmp=[];
                             var deviceV=0;
                             for(var j=0;j<deviceValue.length;j++){
                                 if(bConfigArr[i].id==deviceValue[j].deviceId){
                                     deviceV= deviceValue[j].reportValue;
                                 }
                             }
                             tmp.push(parseFloat(deviceV));
                             tmp.push(bConfigArr[i].xLocation);
                             tmp.push(bConfigArr[i].order);
                             tmp.push(bConfigArr[i].color);
                             tmp.push(bConfigArr[i].code);
                             data_north.push(tmp);
                         }

                         var myChart = echarts.init(document.getElementById(containerId), 'macarons');
                         function data_process(list, n) {
                             let arr = [];
                             for (let i = 0; i < list.length; i++) {
                                 const element = list[i];
                                 // console.log(element);

                                 if (i === list.length - 1) {
                                     arr.push(element)
                                     break;
                                 }

                                 let distX = (list[i + 1][0] - list[i][0]) / n;
                                 let distY = (list[i + 1][2] - list[i][2]) / n;
                                 // console.log(distX);

                                 for (let j = 0; j < n; j++) {
                                     const x = list[i][0] + distX*j ;
                                     const y = list[i][2] + distY*j ;
                                     arr.push([x, element[1], y, element[3], element[4]])
                                 }
                             }
                             // console.log(arr);
                             return arr

                         }


                         function data_yprocess(list, n){
                             let arr = [];
                             for (let i = 0; i < list.length; i++) {
                                 const element = list[i];

                                 if (i === list.length - 1) {
                                     arr.push(element)
                                     break;
                                 }

                                 for (let j = 0; j < n; j++) {
                                     const name = element[1] + j
                                     // console.log("name::", name);

                                     arr.push([element[0], name , element[2], element[3],element[4]])
                                 }
                             }
                             // console.log(arr);
                             return arr
                         }
                         let south = []
                         let middle = []
                         let north = []
                         data = ["depth", "location", "face", "colors","device"],
                         south = data_process(data_south, 40)
                         middle = data_process(data_middle, 40)
                         north = data_process(data_north, 40)

// 扩展
                         data = data.concat(south)
                         data = data.concat(data_yprocess(south,25))
                         data = data.concat(middle)
                         data = data.concat(data_yprocess(middle,40))
                         data = data.concat(north)
                         data = data.concat(data_yprocess(north,25))
                         option = {
                             title:{
                                 text:containerId=="bigForm" ? "水位3D图" : "",
                                 left: 'center',
                                 textStyle:{
                                     fontSize:24,

                                 },
                                 padding:10
                             },
                             tooltip: {},
                             grid: {
                                 top:'1%',
                                 left: '1%',
                                 right: '1%',
                                 bottom: '1%',
                                 containLabel: true
                             },
                             visualMap: {
                                 // ['#333', '#78ab23', 'blue']。意思就是以这三个点作为基准，
                                 // 形成一种『渐变』的色带，数据映射到这个色带上。
                                 // 也就是说，与 visualMap.min 相等的值会映射到
                                 // '#333'，与 visualMap.max 相等的值会映射到 'blue'。
                                 // 对于 visualMap.min 和 visualMap.max 中间的其他点，
                                 // 以所给定的 '#333', '#78ab23', 'blue' 这三个颜色作为
                                 // 基准点进行分段线性插值，得到映射结果。
                                 max: 100,
                                 color:['#333', '#78ab23', 'blue'],
                                 dimension: 'colors'
                             },
                             xAxis3D: {
                                 type: 'category',
                                 name:'位置顺序',

                                 axisTick: {
                                     show:false

                                 },
                                 axisLabel:{
                                     show:false,
                                     color:function(){
                                         if(containerId=="bigForm"){
                                             return '#000';
                                         }else{
                                             return '#fff';
                                         }
                                     }()
                                 }
                             },
                             yAxis3D: {
                                 type: 'category',
                                 name:'两岸及基坑',
                                 axisTick: {
                                     show: false

                                 },
                                 axisLabel:{
                                     show:false,
                                     color:function(){
                                         if(containerId=="bigForm"){
                                             return '#000';
                                         }else{
                                             return '#fff';
                                         }
                                     }()
                                 }
                             },
                             zAxis3D: {
                                 name:'深度'
                             },
                             grid3D: {
                                 // 是否显示三维坐标
                                 // show:true
                             },dataset: {
                                 // 定义了每个维度的名称。这个名称会被显示到默认的 tooltip 中。
                                 dimensions: [
                                     'depth',
                                     'location',
                                     'face',
                                     // 'ordinal' 表示离散型，一般文本使用这种类型。
                                     // {name: 'face', type: 'ordinal'},
                                     'colors',
                                     'device'
                                 ],
                                 source: data
                             },
                             series: [
                                 {
                                     type: 'bar3D',
                                     // symbolSize: symbolSize,
                                     shading: 'lambert',
                                     encode: {
                                         // 将 "face" 列映射到 X 轴。
                                         x: 'face',
                                         y: 'location',
                                         z: 'depth',
                                         // tooltip: [0, 1, 2, 3]
                                     }
                                 }
                             ]
                         }
                         myChart.setOption(option,true);


                     }
                }
            }
        });


    };
    return{
        all_fun:all_fun,
        weathColler:weathColler,
        sysImg:sysImg,
        deviceSet:deviceSet,
        deviceInfo:deviceInfo,
        deviceByHour:deviceByHour,
        drawWeekData:drawWeekData,
        draw3DChart:draw3DChart
    }
})();
function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}

